import cookie from '@/utils/cookie'
import storage from '@/utils/storage'
import api from '@/api'

export default {
  namespaced: true,
  state: {
    info: {},
    token: cookie.get('token') || '',
    location: storage.getItem('location'),
    address: []
  },
  mutations: {
    SET_LOCATION (state, payload) {
      storage.setItem('location', payload, {
        maxAge: 1000 * 60 * 60
      })
      state.location = payload
    },
    SET_ADDRESS (state, payload) {
      state.address = payload
    },
    SET_USET_INFO (state, payload) {
      state.info = payload
    }
  },
  actions: {
    login (context, payload) {
      return api.user.login(payload).then(() => {
        context.dispatch('getUserInfo')
      })
    },
    async getUserInfo ({ commit, dispatch }) {
      const res = await api.user.info()
      commit('SET_USET_INFO', res.data)
      dispatch('getUserAddress')
      dispatch('car/getCarProducts', {}, {root: true})
    },
    async getUserAddress ({ commit }) {
      const res = await api.address.select()
      commit('SET_ADDRESS', res.data)
    },
  }
}
